package edu.clarkson.ee368.spring2012.coreservices;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


@WebServlet("/devices")
public class DeviceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private DocumentBuilder documentBuilder;
	
	@EJB
	private DeviceManager deviceManager;
	
	public DeviceServlet() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			this.documentBuilder = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Document doc = null;
		try {
			doc = documentBuilder.parse(req.getInputStream());
		}
		catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Node commandNode = doc.getFirstChild();
		String command = commandNode.getNodeName();
		if ("register-device".equals(command)) {
			long accountID = Long.parseLong(commandNode.getAttributes().getNamedItem("account-id").getNodeValue());
			long deviceID = Long.parseLong(commandNode.getAttributes().getNamedItem("device-id").getNodeValue());
			deviceManager.setDeviceOnAccount(accountID, deviceID);
			resp.setStatus(200);
		}
	}
	
	

}
